
import 'dart:ui';

import 'package:flutter/material.dart';

import '../flutter_hanzi.dart';

/// 绘制字体时圆基准半径
const _basisRadio = 90.0;

class HanziPainter extends CustomPainter {
  final HanziAniType animationType;
  final Color? color;
  final Animation<double>? repaint;
  final List<PathMetric> metricList;
  final List<Path> strokePathList;
  final int strokeIndex;
  final double scale;

  HanziPainter(
      {this.repaint,
        required this.metricList,
        required this.strokePathList,
        this.strokeIndex = 0,
        required this.scale,
        this.animationType = HanziAniType.once,
        this.color = Colors.black})
      : strokePaint = Paint()..color = color ?? Colors.transparent,
        mDotPaint = Paint()..color = Colors.red,
        super(repaint: repaint);

  final Paint strokePaint;
  final Paint mDotPaint;

  ///保存本次动画进度
  double? aniValue;

  ///
  Path aniPath = Path();

  @override
  void paint(Canvas canvas, Size size) {
    ///不需要动画直接画出来就完事
    if (animationType == HanziAniType.none) {
      for (var i = 0; i < strokePathList.length; ++i) {
        Path path = strokePathList[i];
        canvas.drawPath(path, strokePaint);
      }
    } else {
      if (aniValue == null || repaint!.value < aniValue!) {
        aniPath = Path();
      }
      aniValue = repaint!.value;
      for (var index = 0; index < strokePathList.length; ++index) {
        Path path = strokePathList[index];
        if (index < strokeIndex) {
          canvas.drawPath(path, strokePaint);
        } else if (index == strokeIndex) {
          Tangent? t = metricList[index].getTangentForOffset(metricList[index].length * (aniValue ?? 0));
          Offset point = t!.position;
          double x = point.dx;
          double y = point.dy;
          aniPath.addOval(Rect.fromLTRB(
              x - _basisRadio * scale, y - _basisRadio * scale, x + _basisRadio * scale, y + _basisRadio * scale));
          // print("DEBUG ${DateTime.now()}");
          var combinePath = Path.combine(PathOperation.intersect, aniPath, path);
          // print("INFO ${DateTime.now()}");
          canvas.drawPath(combinePath, strokePaint);
        } else {
          break;
        }
      }
    }

    // for (var median in chineseJson['medians']) {
    //   for (var dot in median) {
    //     canvas.drawCircle(Offset(dot[0], dot[1]), 2, mDotPaint);
    //   }
    // }
    // for (var metric in metricList) {
    //   double length = metric.length / 10;
    //   for (var i = 0; i < length; ++i) {
    //     Tangent? t = metric.getTangentForOffset(i.toDouble() * 10);
    //     canvas.drawCircle(t!.position, 2, mDotPaint);
    //   }
    // }
  }

  @override
  bool shouldRepaint(covariant HanziPainter oldDelegate) {
    return strokePathList != oldDelegate.strokePathList || color != oldDelegate.color;
  }
}